<template>
  <div>
    <el-card>
      <el-button type="primary" icon="Plus" @click="addGrand">
        添加品牌
      </el-button>
      <el-table style="margin: 10px 0px" border :data="grandArr">
        <el-table-column
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column label="品牌名称">
          <template #default="{ row }">
            <h1>
              {{ row.tmName }}
            </h1>
          </template>
        </el-table-column>
        <el-table-column label="品牌LOGO">
          <template #default="{ row }">
            <img :src="row.logoUrl" alt="" style="width: auto; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #default="{ row }">
            <el-button
              type="primary"
              icon="Edit"
              color="#eca93f"
              @click="edit(row)"
            ></el-button>
            <el-popconfirm
              :title="`你确定要删除这个${row.tmName}吗`"
              icon="Delete"
              width="260px"
              @confirm="confirmDelete(row.id)"
            >
              <template #reference>
                <el-button
                  type="primary"
                  icon="Delete"
                  color="#ff6e67"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!--  <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[3, 5, 7, 9]"
        :disabled="false"
        :background="true"
        layout=" prev, pager, next, jumper,->,sizes,total"
        :total="totalGrand"
        @current-change="getGrand"
        @size-change="changePage"
      /> -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 7, 9]"
        :disabled="false"
        :background="true"
        layout=" prev, pager, next, jumper,->,sizes,total"
        :total="totalGrand"
        @current-change="getGrand"
        @size-change="changePage"
      />
    </el-card>
    <el-dialog
      v-model="visible"
      :title="getGrandInfo.id ? '修改品牌' : '添加品牌'"
      width="500"
    >
      <el-form :rules="rules" :model="getGrandInfo" ref="form">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input width="100px" v-model="getGrandInfo.tmName"></el-input>
        </el-form-item>
        <el-form-item label="上传文件" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="getGrandInfo.logoUrl"
              :src="getGrandInfo.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <!-- 具名插槽:footer -->
      <template #footer>
        <el-button type="primary" size="default" @click="cancel">
          取消
        </el-button>
        <el-button type="primary" size="default" @click="confirm">
          确定
        </el-button>
      </template>
      <!-- 具名插槽用于显示取消和确认 -->
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqGrand,
  reqUpdateGrand,
  reqDeleteGrand,
} from '../../../api/product/grand'
import type { data, records } from '../../../api/product/grand/type'
import { ElMessage } from 'element-plus'
let currentPage = ref<number>(1)
let pageSize = ref<number>(5)
let totalGrand = ref<number>(0)
let grandArr = ref<any>([])
let visible = ref(false)
let form = ref()
//用于收集所填写的品牌信息
let getGrandInfo = reactive<records>({
  tmName: '',
  logoUrl: '',
})
const getGrand = async () => {
  /* currentPage.value = page; */
  let result: data = await reqGrand(currentPage.value, pageSize.value)
  /*   console.log(result) */
  if (result.code == 200) {
    totalGrand.value = result.data.total
    grandArr.value = result.data.records
  }
}
onMounted(() => {
  getGrand()
})

function changePage() {
  //当前每一页的数据量发生变化时，当前页码归1
  currentPage.value = 1
  getGrand()
}
async function confirm() {
  await form.value.validate()

  //点击确定发送post请求
  let result = await reqUpdateGrand(getGrandInfo)
  console.log(result)
  if (result.code == 200) {
    //关闭弹窗
    visible.value = false
    //重新渲染品牌内容
    getGrand()
    //弹出对话框
    ElMessage({
      type: 'success',
      message: getGrandInfo.id ? '修改成功' : '添加成功',
    })
  } else {
    ElMessage({
      type: 'error',
      message: getGrandInfo.id ? '修改失败' : '添加失败',
    })
  }
}

function cancel() {
  visible.value = false
}

function addGrand() {
  form.value?.clearValidate()
  visible.value = true

  getGrandInfo.logoUrl = ''
  getGrandInfo.tmName = ''
  getGrandInfo.id = undefined
}
//编辑品牌
function edit(row: records) {
  //清空表单验证信息
  nextTick(() => {
    form.value.clearValidate('tmName')
  })
  console.log(row)
  //es6对象合并方法实现以下三行数据的赋值
  Object.assign(getGrandInfo, row)
  /* getGrandInfo.tmName = row.tmName
  getGrandInfo.logoUrl = row.logoUrl
  getGrandInfo.id = row.id */
  visible.value = true
  /* form.value.clearValidate() */
}
//上传文件之前触发的钩子
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: any) => {
  if (rawFile.type == 'image/jpg' || rawFile.type == 'image/png') {
  } else {
    ElMessage({
      type: 'error',
      message: '请上传jgp格式或者png格式的图片',
    })
    return false
  }
}
//上传成功之后触发的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  //response表示上传成功之后返回的对象
  response: any,
) => {
  /*   console.log(response); */
  getGrandInfo.logoUrl = response.data
  form.value.clearValidate()
}
//定义校验规则
const validateName = (rule: any, value: any, callBack: any) => {
  //trim用于去除字段首尾空格
  if (value.trim().length > 2) {
    callBack()
  } else {
    //校验未通过，返回的错误信息
    callBack(new Error('品牌名称应大于等于两位'))
  }
}
//定义文件上传校验规则
const validateLogo = (rule: any, value: any, callBack: any) => {
  if (value) {
    callBack()
  } else {
    callBack(new Error('请选择文件'))
  }
}

//定义表单校验规则对象
const rules = {
  tmName: [{ required: true, trigger: 'blur', validate: validateName }],
  logoUrl: [{ required: true, trigger: 'blur', validate: validateLogo }],
}
//定义确定删除品牌的方法
async function confirmDelete(id: number) {
  //调用删除接口
  let result = await reqDeleteGrand(id)
  /*  console.log(result) */

  if (result.code == 200) {
    //删除成功，重新渲染数据
    getGrand()
    //提示删除成功的消息
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
  } else {
    ElMessage({
      type: 'error',
      message: '操作失败',
    })
  }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
